﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Features.Util;

namespace Trentacular.SharePoint.Features.FeatureReceivers
{
    public class CAExtensionsFeatureReceiver : BaseFeatureReceiver<SPWebApplication>
    {
        public override void FeatureActivated(SPWebApplication webApp, SPFeatureReceiverProperties properties)
        {
            if (!webApp.IsAdministrationWebApplication)
                throw new InvalidOperationException("The Central Administration Extensions Feature can only be activated on the Web Application hosting Central Administration");

            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.EnsureActivated(Config.CentralAdminCustomActionsFeatureID);
            }
        }

        public override void FeatureDeactivating(SPWebApplication webApp, SPFeatureReceiverProperties properties)
        {
            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.Remove(Config.CentralAdminCustomActionsFeatureID);
            }
        }
    }
}
